#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "stack.h"

struct Stack_Node {
	Element value;
	struct Stack_Node *link;
};

void
init_stack(Stack *stack)
{
	stack->top = NULL;
}

void
push(Stack *stack, Element elem)
{
	struct Stack_Node *tp;
	if((tp = malloc(sizeof(struct Stack_Node))) == NULL) {
		fprintf(stderr, "malloc error in push\n");
		exit(1);
	}
	tp->value = elem;
	tp->link = stack->top;
	stack->top = tp;
}

void
pop(Stack *stack)
{
	struct Stack_Node *tp;
	if(isEmpty(stack)) {
		fprintf(stderr, "error in pop: stack empty\n");
		return;
	}
	tp = stack->top;
	stack->top = stack->top->link;
	free(tp);
}

Element
top(Stack *stack)
{
	if(isEmpty(stack)) {
		fprintf(stderr, "error in top: stack empty\n");
		return;
	}
	return stack->top->value;
}

int
isEmpty(Stack *stack)
{
	return stack->top == NULL;
}

void
destroy_stack(Stack *stack)
{
	struct Stack_Node *tp;
	while(!isEmpty(stack)) {
		tp = stack->top;
		stack->top = stack->top->link;
		printf("des: %d\n", tp->value);
		free(tp);
	}
}
